<?php

namespace addons\qingdong\model;

use think\Exception;
use think\Model;
use traits\model\SoftDelete;

/**
 * 审批管理
 */
class Approval Extends Model {
	use SoftDelete;
    // 表名,不含前缀
    protected $name = 'qingdong_approval';
	// 开启自动写入时间戳字段
	protected $autoWriteTimestamp = 'int';
	// 定义时间戳字段名
	protected $createTime = 'createtime';
	protected $updateTime = 'updatetime';
	protected $deleteTime = 'deletetime';
    // 追加属性
    protected $append = [
        'show_staff_data',
    ];
    public function getShowStaffDataAttr($value,$data)
    {
        if (!isset($data['show_staff_id'])) {
            return '';
        }
        $ids=explode(',',$data['show_staff_id']);
        return Staff::where(['id'=>['in',$ids]])->field('id,name,img,post,mobile')->select();
    }

	/**
	 * @desc 备注
	 * @update_date 2021/7/10 更新时间
	 * @author zhangwei
	 */
	public static function createApproval($params) {
		$data            = $params['data'];
		$formapproval_id = $params['formapproval_id'];
		$relation_type   = $params['relation_type']??'';
		$relation_id     = $params['relation_id']??0;
		$flow_staff_id     = $params['flow_staff_ids']??'';
        $file_ids     = $params['file_ids']??'';

		$add = [
			'content'         => json_encode($data),
			'formapproval_id' => $formapproval_id,
			'relation_id'     => $relation_id,
			'flow_staff_ids'     => $flow_staff_id,
			'file_ids'     => $file_ids,
			'check_status'     => 1,
		];
        if(isset($params['reminds_id'])){
            $add['reminds_id']=$params['reminds_id'];
        }
		$staff = Staff::info();
		if ($staff) {
			$add['create_staff_id'] = $staff->id;
		}
        $add['show_staff_id']=$add['create_staff_id'];

        $flow = Flow::getsteplist(Flow::APPROVAL_STATUS.'_'.$formapproval_id);
        $add['flow_id'] = $flow['flow_id'];
        $add['order_id'] = $flow['order_id'];

        if ($flow['status'] == 0) {//发起人自选
            if (empty($add['flow_staff_ids'])) {
                throw new Exception('审批人必须选择');
            }
            $add['flow_staff_ids'] = trim($params['flow_staff_ids']);
        } else {
            $add['flow_staff_ids'] = trim($flow['flow_staff_ids']);
        }
		$model = new self;
		// 调用当前模型对应的User验证器类进行数据验证
		$result = $model->allowField(true)->save($add);
		if (false === $result) {
			// 验证失败 输出错误信息
			throw new Exception($model->getError());
		}
		$lastId = $model->getLastInsID();

        if ($flow['status'] == 1) {//固定审批
            //发送审批通知
            Flow::sendStepRecord($flow,Flow::APPROVAL_STATUS, $lastId);
        } else {//发起人自选 依次审批
            $staff_id   = explode(',', $params['flow_staff_ids'])[0];
            if ($staff_id) {
                ExamineRecord::addExaminse(ExamineRecord::APPROVAL_TYPE, $lastId, $staff_id);
            }
        }

		//创建日志
		OperationLog::createLog(OperationLog::APPROVAL_TYPE, $lastId, '创建');

		return $lastId;
	}

    //修改
    public static function updateApproval($params) {
        $data            = $params['data'];
        $formapproval_id = $params['formapproval_id'];
        $relation_type   = $params['relation_type'];
        $relation_id     = $params['relation_id']??0;
        $flow_staff_id     = $params['flow_staff_ids']??'';
        $file_ids     = $params['file_ids']??'';

        $update = [
            'content' => json_encode($data),
            'file_ids' => $file_ids,
            'formapproval_id' => $formapproval_id,
            'relation_type' => $relation_type,
            'relation_id' => $relation_id,
            'flow_staff_ids' => $flow_staff_id,
            'check_status' => 1,
            'next_staff_id' => explode(',', $flow_staff_id)[0]
        ];

        $flow = Flow::getsteplist(Flow::APPROVAL_STATUS.'_'.$formapproval_id);
        $update['flow_id'] = $flow['flow_id'];
        $update['order_id'] = $flow['order_id'];

        if ($flow['status'] == 0) {//发起人自选
            if (empty($update['flow_staff_ids'])) {
                throw new Exception('审批人必须选择');
            }
            $update['flow_staff_ids'] = trim($params['flow_staff_ids']);
        } else {
            $update['flow_staff_ids'] = trim($flow['flow_staff_ids']);
        }
        $model = new self;
        // 调用当前模型对应的User验证器类进行数据验证
        $result = $model->allowField(true)->save($update,['id'=>$params['id']]);
        if (false === $result) {
            // 验证失败 输出错误信息
            throw new Exception($model->getError());
        }

        if ($flow['status'] == 1) {//固定审批
            //发送审批通知
            Flow::sendStepRecord($flow,Flow::APPROVAL_STATUS, $params['id']);
        } else {//发起人自选 依次审批
            $staff_id   = explode(',', $params['flow_staff_ids'])[0];
            if ($staff_id) {
                ExamineRecord::addExaminse(ExamineRecord::APPROVAL_TYPE, $params['id'], $staff_id);
            }
        }
        //创建日志
        OperationLog::createLog(OperationLog::APPROVAL_TYPE, $params['id'], '修改');

        return true;
    }
//
    public function getFileidsAttr($value) {
        $files  = explode(',', $value);
        $result = [];
        foreach ($files as $fid) {
            if ($fid) {
                $result[] = cdnurl(File::getUrl($fid), true);
            }
        }

        return $result;
    }
	//获取内容
    public function getContent($value){
	    return json_decode($value,true);
    }
    //创建人
    public function createStaff() {
        return $this->hasOne(Staff::class, 'id', 'create_staff_id')->field('id,name,img');
    }
    //
    public function formapproval() {
        return $this->hasOne(FormApproval::class, 'id', 'formapproval_id')->field('id,name,form_id');
    }
    //获取时间
    public function getCreatetimeAttr($value){
	    return date('Y-m-d H:i',$value);
    }
    //获取内容
    public function getContentAttr($value){
	    return json_decode($value,true);
    }
}
